<template>
  <div class="back-top">
    <button class="btn-fab" v-show="isShow" @click="toTop">
      <i class="icon icon-less"></i>
      <span>TOP</span>
    </button>
  </div>
</template>

<script>
export default {
  name: 'BackTop',
  data () {
    return {
      isShow: false,
      target: ''
    }
  },
  methods: {
    showIcon () {
      if (document.documentElement.scrollTop > 100 || window.pageYOffset > 100 || document.body.scrollTop > 100) {
        this.isShow = true
      } else if (document.documentElement.scrollTop < 100 || window.pageYOffset < 100 || document.body.scrollTop < 100) {
        this.isShow = false
      }
    },
    toTop () {
      let self = this
      let timer = setInterval(() => {
        // 各浏览器下 scrollTop 的差异
        let top = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop
        let speed = Math.ceil(top / 5)
        
        document.documentElement.scrollTop = top - speed
        window.pageYOffset = top - speed
        document.body.scrollTop = top - speed

        if (top <= 0) {
          clearInterval(timer)
        }
      }, 20)
    }
  },
  mounted () {
    if(window.addEventListener) {
      window.addEventListener('scroll', this.showIcon)
    } else if(window.attachEvent) {
      window.attachEvent('onscroll', this.showIcon)
    }
    
  },
  beforeDestroy () {
    // 组件销毁的时候，需要删除scroll的监听事件。
    window.removeEventListener('scroll', this.showIcon)
    
  }
}
</script>

<style scoped>
.back-top {
  position: fixed;
  bottom: 150px;
  right: 20px;
  z-index: 2;
}
.back-top button {
  border: none;  
}
.back-top .btn-fab {
  width: 110px;
  height: 110px;
  border-radius: 50%;
  background-color: rgba(0,0,0,0.5);
  color: #fff;
}
.back-top .btn-fab .icon {
  font-size: 35px;
}
</style>

